package club.zhilin.guli.infrastructure.gateway.filter;

import club.zhilin.guli.common.base.util.JwtUtil;
import com.google.gson.JsonObject;
import io.jsonwebtoken.lang.Collections;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author zhilin
 * @since 2022/3/5 18:31
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断路径中如果含有 /portal/**/auth/**
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher();
        if (matcher.match("/portal/**/auth/**", path)) {
            List<String> authorization = request.getHeaders().get("Authorization");
            // 没有token
            if (authorization == null || Collections.isEmpty(authorization)) {
                return fluxOut(exchange.getResponse());
            }
            // token校验失败
            if (!JwtUtil.checkJwtToken(authorization.get(0))) {
                return fluxOut(exchange.getResponse());
            }
        }
        return chain.filter(exchange);
    }

    /**
     * 定义当前过滤器的优先级,值越小,优先级越高
     *
     * @return 过滤器的优先级
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 使用webflux输出响应信息
     *
     * @param response 响应对象
     * @return webflux输出响应信息
     */
    private Mono<Void> fluxOut(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "");
        message.addProperty("message", "鉴权失败");
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
